/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.validator;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.MethodUtils;

public class Rule {

	private String name;
	private String clazz;
	private String method;
	private String msg;
	private String resourceBundle;

	private static Map<String, Object> objectMap = null;
	static {
		objectMap = new HashMap<String, Object>();
	}

	public static Object getObject(Class<?> clazz) throws Exception {
		return getObject(clazz.getName());
	}

	public static Object getObject(String clazz) throws Exception {
		Object object = objectMap.get(clazz);
		if (object == null) {
			object = Class.forName(clazz).newInstance();
			objectMap.put(clazz, object);
		}
		return object;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name.trim();
	}

	public String getClazz() {
		return clazz;
	}

	public void setClazz(String clazz) {
		this.clazz = clazz.trim();
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method.trim();
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg.trim();
	}

	public String getResourceBundle() {
		return resourceBundle;
	}

	public void setResourceBundle(String resourceBundle) {
		this.resourceBundle = resourceBundle;
	}
	
	public Boolean validate(Map<String, Object> map) throws Exception {
		Object object = getObject(getClazz());
		try {
			return (Boolean) MethodUtils.invokeMethod(object, getMethod(), new Object[] { map }, new Class[] { Map.class });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public String toString() {
		return name;
	}
}